package com.lujianfei.common

import android.app.Activity
import android.content.Intent
import android.net.Uri


/**
 * Author: lujianfei
 * Date: 2023/11/1 11:29
 * Description: 相册获取工具
 */

class AlbumHelper {
    companion object {
        private const val ALBUM_CODE = 100
    }

    var onUriCallback:((Uri)->Unit)?= null
    fun openAlbum(activity:Activity, onUriCallback:(Uri)->Unit) {
        this.onUriCallback = onUriCallback
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*|video/*"
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        activity.startActivityForResult(intent, ALBUM_CODE)
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            ALBUM_CODE -> {
                val clipData = data?.clipData
                if (clipData != null) {
                    val clipData = data.clipData
                    if (clipData != null) {
                        for (i in 0 until clipData.itemCount) {
                            val uri = clipData.getItemAt(i).uri
                            this.onUriCallback?.invoke(uri)
                        }
                    }
                } else {
                    data?.data?.let { this.onUriCallback?.invoke(it) }
                }
            }
        }
    }
}